<template>
  <div
    :id="id"
    style="height: 100%"
    class="dplayer"
    @dblclick="fullScreen"
  ></div>
</template>

<script>
import Flv from "flv.js";
import DPlayer from "dplayer";

export default {
  props: {
    playerOption: Object,
    id: {
      type: String,
      default: "videojs-flvjs",
    },
  },
  data() {
    return {
      player: null,
      isFullScreen: false,
      flvPlayer: null,
      isFist: false,
    };
  },
  methods: {
    initDPlayer() {
      const options = {
        container: document.getElementById(this.id),
        autoplay: true,
        screenshot: true,
        hotkey: false,
        live: true,
        volume: 0,
        mutex: false,
        video: {
          url: this.playerOption.url,
          type: "customFlv",
          customType: {
            customFlv: (video, player) => {
              this.flvPlayer = Flv.createPlayer({
                type: "flv",
                url: video.src,
              });
              this.flvPlayer.attachMediaElement(video);
              this.flvPlayer.load();
            },
          },
        },
      };
      this.player = new DPlayer(options);
      this.player.on("play", () => {
        if (that.isFist) {
          // 重新实例化播放器
          that.playLive();
          that.isFist = false;
        }
      });
      this.player.on("pause", () => {
        that.isFist = true;
      });
    },
    playLive() {
      // 先销毁再重新加载
      if (this.flvPlayer) {
        this.flvPlayer.destroy();
        this.player.destroy();
      }
      this.initDPlayer();
    },
    fullScreen() {
      if (this.isFullScreen) {
        this.player.fullScreen.cancel("browser");
        this.isFullScreen = false;
      } else {
        this.player.fullScreen.request("browser");
        this.isFullScreen = true;
      }
    },
    destory() {
      // 该方法是在父组件销毁时调用的销毁播放器及播放流的
      this.flvPlayer.destroy();
      this.player.destroy();
      this.flvPlayer = null;
      this.player = null;
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initDPlayer();
    });
  },
};
</script>
<style scoped>
.dplayer /deep/ .dplayer-video-current {
  width: auto;
  max-height: 100%;
  margin: 0 auto;
}

.dplayer /deep/ .dplayer-video-wrap {
  height: 100%;
}

.dplayer /deep/ .dplayer-video {
  height: 100%;
}

.dplayer {
  height: 100%;
}
</style>
